package cn.tedu.lbs.basic.web.service;

import cn.tedu.lbs.basic.web.repository.AdminRepository;
import cn.tedu.lbs.basic.web.repository.UserGroupRepository;
import cn.tedu.lbs.basic.web.util.AuthenticationContextUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tarena.lbs.base.common.utils.Asserts;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.passport.enums.Roles;
import com.tarena.lbs.common.passport.principle.UserPrinciple;
import com.tarena.lbs.pojo.basic.param.UserGroupParam;
import com.tarena.lbs.pojo.basic.po.AdminPO;
import com.tarena.lbs.pojo.basic.po.UserGroupPO;
import com.tarena.lbs.pojo.basic.query.UserGroupQuery;
import com.tarena.lbs.pojo.basic.vo.UserGroupVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserGroupService {
    @Autowired
    private UserGroupRepository userGroupRepository;
    @Autowired
    private AdminRepository adminRepository;
    public PageResult<UserGroupVO> pageList(UserGroupQuery query) throws BusinessException {
        //1.检查用户认证解析结果 读取admin详情 拿到businessId
        Integer businessId = checkAndGetBusinessId();
        //2.使用仓储层读取 列表数据
        List<UserGroupPO> pos= getUserGroups(businessId);
        //3.封装分页对象
        return assemblePageResult(pos);
    }

    private PageResult<UserGroupVO> assemblePageResult(List<UserGroupPO> pos) {
        PageResult<UserGroupVO> voPage=new PageResult<>(10,1);
        voPage.setTotal(100L);
        if (pos!=null&&pos.size()>0){
            voPage.setObjects(pos.stream().map(po -> {
                UserGroupVO vo = new UserGroupVO();
                BeanUtils.copyProperties(po, vo);
                return vo;
            }).collect(Collectors.toList()));
        }
        return voPage;
    }

    private List<UserGroupPO> getUserGroups(Integer businessId) {
        //select * from lbs_user_group where business_id=?
        QueryWrapper<UserGroupPO> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("business_id",businessId);
        return userGroupRepository.list(queryWrapper);
    }

    private Integer checkAndGetBusinessId() throws BusinessException {
        //1.拿到认证对象
        UserPrinciple userPrinciple = AuthenticationContextUtil.get();
        //2.断言空
        Asserts.isTrue(userPrinciple==null,new BusinessException("-2","用户认证解析失败"));
        //3.拿到角色
        Roles role = userPrinciple.getRole();
        Integer businessId=null;
        //4.如果角色是SHOP 需要给businessId赋值
        if (role==Roles.SHOP){
            AdminPO po = adminRepository.getById(userPrinciple.getId());
            Asserts.isTrue
                    (po==null,new BusinessException("-2","登录用户根本不存在"));
            businessId=po.getBusinessId();
        }
        return businessId;
    }

    public void addGroup(UserGroupParam param) throws BusinessException {
        //1.获取用户id 从而检查并获取需要关联的商家
        Integer businessId = checkAndGetBusinessId();
        //2.判断当前商家人群是否已经存在 select count(*) from lbs_user_group
        //where business_id=? and group_name=?
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("business_id",businessId);
        queryWrapper.eq("group_name",param.getGroupName());
        long count = userGroupRepository.count(queryWrapper);
        Asserts.isTrue(count>0,new BusinessException("-2","人群已经存在"));
        //3.组织po
        UserGroupPO po=new UserGroupPO();
        BeanUtils.copyProperties(param,po);
        po.setBusinessId(businessId);
        po.setCreateAt(new Date());
        userGroupRepository.save(po);
    }

    public List<Integer> getUserGroupIds(Integer userId, Integer businessId) {
        //自定义sql 查询用户所属人群列表
        return userGroupRepository.getUserGroupIds(userId,businessId);
    }
}
